package com.quan.weixin.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quan.common.bean.PageBean;
import com.quan.common.core.MyBaseServiceImpl;
import com.quan.common.utils.RedisUtils;
import com.quan.weixin.entity.WeixinSubscribe;
import com.quan.weixin.mapper.WeixinSubscribeMapper;
import com.quan.weixin.service.WeixinSubscribeService;

/**
 * <p>
 * 微信用户关注 服务实现类
 * </p>
 *
 * @author 杨浩泉
 * @since 2019-11-12
 */
@Service
public class WeixinSubscribeServiceImpl extends MyBaseServiceImpl<WeixinSubscribeMapper, WeixinSubscribe> implements WeixinSubscribeService {
	
	@Autowired
	private WeixinSubscribeMapper mapper;

	@Autowired
	private RedisUtils redisUtils;
	
	
	@Override
	public IPage<WeixinSubscribe> selectMyPage(WeixinSubscribe entity, PageBean pageBean) {
		Page<WeixinSubscribe> page = new Page<>(pageBean.getPage(), pageBean.getLimit());
		
		// 排序
		if(StringUtils.isNotBlank(pageBean.getSortOrder()) && StringUtils.isNotBlank(pageBean.getSortName())) {
			List<OrderItem> orders = new ArrayList<OrderItem>();
			OrderItem orderItem = new OrderItem();
			orderItem.setColumn(pageBean.getSortName());
			orderItem.setAsc(!pageBean.getSortOrder().equalsIgnoreCase("DESC"));
			orders.add(orderItem);
			page.setOrders(orders);
		}
		return this.mapper.selectMyPage(page, entity);
	}
	
	@Override
	public WeixinSubscribe loadSubscribe() {
		String text = this.redisUtils.get("weixin:subscribe");
		if(StringUtils.isNotBlank(text)) {
			return JSON.parseObject(text, WeixinSubscribe.class);
		} else {
			QueryWrapper<WeixinSubscribe> queryWrapper = new QueryWrapper<WeixinSubscribe>();
			queryWrapper.last("limit 1");

			List<WeixinSubscribe> list = super.list(queryWrapper);

			if (null != list && !list.isEmpty()) {
				this.redisUtils.set("weixin:subscribe", JSON.toJSONString(list.get(0)));
				return list.get(0);
			}
		}
		return null;
	}

	@Override
	public boolean saveOrUpdate(WeixinSubscribe entity) {
		return super.saveOrUpdate(entity);
	}


}
